function S3QLquery(s3ql)
	{
	/*Function S3QLQuery builds the S3QL query for any remote uri
	#INPUT: s3ql is an array with at least key and url
	#OUTPUT: a string, containing the URI with the information on the input element UID 
	s3ql = new Array();s3ql['url'] = 'http://ibl.mdanderson.org/TCGA/';s3ql['key'] = 'mudamseostempos';s3ql['where'] = new Array();s3ql['from'] = 'statements';s3ql['where']['rule_id']='191';
	*/
	
	var wrap='';
	
	wrap = s3ql['url'] + '/S3QL.php';
	
	if (s3ql['user_id']!=null) {
		wrap += '?user_id=' + s3ql['user_id'];
	}
	if (s3ql['format']!=null) {
		( s3ql['user_id']==null)? r = '?': r = '&';
		wrap +=  r + 'format=' + s3ql['format'];
	}
	
	( s3ql['user_id']==null && s3ql['format']==null )? r = '?': r = '&';
	wrap += r  + 'query=<S3QL>'; 
	wrap += '<key>' + s3ql['key'] + '</key>';

	//remove the elements already used to build the query, keep the rest
	delete s3ql['url'];	delete s3ql['key']; delete s3ql['user_id']; delete s3ql['format'];
	 
	for (var i in s3ql) {
	       var field = i;
		   var val = s3ql[i];
		   var go = (is_array(val) || is_string(val));
		   if(go){
		   if(!is_array(s3ql[field])) //if is not an array, just build the simple xml
			wrap += '<' + field + '>' + s3ql[field] + '</' + field + '>';
			else //for arrays, build the nested xml
			{wrap += '<' + field + '>';
			for (var j in val)
				{
				
				var subfield = j;
				var subvalue = val[subfield];
				var go = (is_array(subvalue) || is_string(subvalue));
				if (go) {
				wrap += '<' + subfield + '>' + subvalue + '</' + subfield + '>';
				}
				}
			wrap += '</' + field + '>';
			}
			}
		}
		wrap += '</S3QL>';
		
	 return (wrap);
	
		
	}

function itemStatInserted(stat, value, item, rule, button_id) {
   if(stat[0]['statement_id'])
   document.getElementById(button_id).innerHTML = value+'<br /><font color="#66CC00">inserted</font>';
   else {
   document.getElementById(button_id).innerHTML = value+'<br /><font color="#FF0000">NOT inserted: '+stat[0]['message']+'</font>';    
   }
}

function insertItemStat(item,value, rule, button_id) {
	var s3ql = new Array;
	s3ql['url']=document.getElementById('url').value;
	s3ql['key']=document.getElementById('key').value;
	s3ql['insert'] = 'statement';
	s3ql.where = new Array;
	s3ql['where']['item_id']=item;
	s3ql['where']['rule_id'] = rule;
	s3ql['where']['value'] = value;
	s3ql['format'] = 'json';
	var url = S3QLquery(s3ql);
	
	s3db_jsonpp_call(url,"itemStatInserted(ans, '" + value + "','" + item + "', '" + rule + "', '"+button_id+"')");   
}




function findItem(collection, notes, button_id,event)
{
if(event && event.keyCode==13){
document.getElementById(button_id).innerHTML = 'processing ...';

if(!notes){
button_id.innerHTML = 'Please input some label';
}
else {

var s3ql = new Array;
s3ql['url']=document.getElementById('url').value;
s3ql['key']=document.getElementById('key').value;
s3ql['select'] = '*';
s3ql['from'] = 'items';
s3ql.where = new Array;
s3ql['where']['collection_id'] = collection;
s3ql['where']['notes'] = notes;
s3ql['format'] = 'json';
var url = S3QLquery(s3ql);

item=s3db_jsonpp_call(url,"itemFound(ans, '" + notes + "','" + collection + "', '" + button_id + "')");
return item
}
}
}



function insertItem(collection, label, button_id) {
     url=document.getElementById('url').value;
	 key=document.getElementById('key').value;
	 s3ql = new Array;
	    s3ql['url']=document.getElementById('url').value;
	    s3ql['key']=document.getElementById('key').value;
		s3ql['insert']='item';
	    s3ql['where'] = new Array;
	    s3ql['where']['collection_id']=collection;
	    s3ql['where']['notes']=label;
	   
		var url = S3QLquery(s3ql);

		//s3db_jsonpp_call(url,'displayItemButton(ans, \''+ collection +'\',\''+ label +'\', \''+ button_id +'\')');
		  s3db_jsonpp_call(url,'itemInserted(ans, \''+label+'\',\''+collection+'\',\''+button_id+'\')');
		 
	
}


function findAllItemStatements(item, url, key, collection, collectionRules) {
   //Build an array to query last inserted item on collceton
  s3ql = new Array();
  s3ql['url'] = url;
  s3ql['key'] = key;
  s3ql['from'] = 'statements';
  s3ql['where'] = new Array();
  s3ql['where']['item_id']=item;
  q = S3QLquery(s3ql);
  s3db_jsonpp_call(q,'writeAllItemStatementsOnText(ans, \''+ item +'\', \''+ url +'\', \''+ key +'\', \''+collectionRules+'\')'); 

}



function findRule(rule, url, key,button_id) {
    var s3ql = new Array();
	  
	  s3ql.url=url;
	  s3ql.key=key;
	  s3ql.from='rules';
	 
	  s3ql.where =new Array();
	  s3ql['where']['rule_id']=rule+'';	  
	  
	  var url = S3QLquery(s3ql);
	  
	   s3db_jsonpp_call(url,'RuleFound(ans, \''+ rule +'\', \''+button_id+'\')');
}



function findKey(url, username, pass) {
     q = url+'/apilogin.php?username='+username+'&password='+pass+'&format=json';
	 s3db_jsonpp_call(q,'keyFound(ans)');

}


function findProjectRules(url,key) {
   
	document.getElementById('collections').innerHTML = 'processing ...';
	var project = document.getElementById('project_id').value;
	var s3ql = new Array();
   s3ql.url=url;
   s3ql.key=key;
   s3ql.from='rules';
   s3ql.where = new Array();
   s3ql.where['project_id'] = project;
   s3ql.where['object'] = '!=\'UID\'';
   var q = S3QLquery(s3ql);
   s3db_jsonpp_call(q,'projectRulesFound(ans, \'rules\')');

   //To obtain a collection reference, display collections
   s3ql.url=url;
   s3ql.key=key;
   s3ql.from='collection';
   s3ql.where = new Array();
   s3ql.where['project_id'] = project;
   
   var q = S3QLquery(s3ql);
   s3db_jsonpp_call(q,'projectCollectionsFound(ans, \'collections\')');


}



function findProjects(url,key, button_id) {
   var s3ql = new Array();
   s3ql.url=url;
   s3ql.key=key;
   s3ql.from='projects';
   
   var q = S3QLquery(s3ql);
   s3db_jsonpp_call(q,'projectsFound(ans, \''+button_id+'\')');
}

function findLastInsertedItem(collection, url,key) {
  
  //Build an array to query last inserted item on collceton
  s3ql = new Array();
  s3ql['url'] = url;
  s3ql['key'] = key;
  s3ql['from'] = 'items';
  s3ql['where'] = new Array();
  s3ql['where']['collection_id']=collection;
  s3ql['order_by']='created_on desc';
  s3ql['limit']='1';
  q = S3QLquery(s3ql);
  s3db_jsonpp_call(q,'lastIntertedItemFound(ans, \''+ collection +'\', \''+ url +'\', \''+ key +'\')'); 

}


function s3db_jsonpp_call (src,next_eval) {
     call = "call_"+Math.random().toString().replace(/\./g,"");//alert("787");
     var headID = document.getElementsByTagName("head")[0];
     var script = document.createElement('script');
     script.id = call;
     script.type = 'text/javascript';
     // using padded, parameterized JSON
     src=src+"&format=json&jsonp=s3db_jsonpp&jsonpp="+next_eval+"&onload=remove_element_by_id('"+script.id+"')";
     script.src = src ;//window.open(src);
     headID.appendChild(script); // retrieve answer
    
	 }
 
function remove_element_by_id (id) {
    var e = document.getElementById(id);
    e.parentNode.removeChild(e);
    return false}

function s3db_jsonpp (ans,jsonpp) {
    eval(jsonpp);
    return ans
	}

